import React, { useEffect, useState } from "react";
import { Button, Form, Input, Table, Popconfirm, Modal, InputNumber, Select, DatePicker } from "antd";
import './user.css'
import { getUser, addUser, editUser,delUser } from "../../api/index";
import dayjs from "dayjs";

const User = () => {

    //搜索值
    const [listData, setlistData] = useState({
        name: ''
    })
    //判断是新增还是编辑
    const [modaltype, setmodaltype] = useState(0)
    //表格的数据
    const [tableData, settableData] = useState([])
    //判断弹窗打开还是关闭
    const [isModalVisible, setisModalVisible] = useState(false)
    const [form] = Form.useForm()
    const handleClick = (type, rowData) => {
        setisModalVisible(!isModalVisible)
        if (type === 'add') {
            setmodaltype(0)
        } else {
            setmodaltype(1)
            console.log(rowData, 'rowdata')
            //需要对当前行的数据进行深拷贝
            const cloneData = JSON.parse(JSON.stringify(rowData))
            cloneData.birth = dayjs(cloneData.birth)
            //表单数据回填
            form.setFieldsValue(cloneData)
        }
        console.log('点击了按钮')
    }
    //处理表单的提交
    const handleQuery = (value) => {
        console.log(value.keyword)
        //setlistData是异步的,先执行getTableData,再执行setlistData，所以第一次的时候，name是空，第二次执行的时候，name的值已经由上一次的赋值了，所以需要重新获取一次数据
        setlistData({ name: value.keyword })
        getTableData()
        
    }
    useEffect(()=>{
        getTableData()

    },[listData])
    useEffect(() => {
        //获取用户的列表数据
        getUser(listData).then((res) => {

            console.log(res.list)
            settableData(res.list)
        })

    }, [])
    //删除
    const handleDelete = ({id}) => {
        // const id = JSON.stringify(rowData.id)
        //??为什么这样不行
      
        delUser({id}).then(() => {

            getTableData()
        })
    }
    const getTableData = () => {
        getUser(listData).then((res) => {
            settableData(res.list)
        })
    }
    //弹窗确定
    const handleOk = () => {
        //表单校验
        form.validateFields().then((res) => {

            console.log(res)
            //需要处理日期的格式,使用dayjs
            res.birth = dayjs(res.birth).format('YYYY-MM-DD')
            if (modaltype) {
                //编辑
                editUser(res).then((res) => {
                    //编辑的时候是没有id值的
                    console.log(res)
                    setisModalVisible(false)
                    form.resetFields()
                    getTableData()

                })
            } else {
                //新增
                addUser(res).then((res) => {
                    console.log(res)
                    setisModalVisible(false)
                    form.resetFields()
                    //清空表单的数据
                    getTableData()
                })
            }
        }).catch((err) => {
            console.log(err)
        })
        setisModalVisible(false)

    }
    //弹窗取消
    const handleCancel = () => {
        setisModalVisible(false)
    }
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name'
        },
        {
            title: '年龄',

            dataIndex: 'age'
        },
        {
            title: '性别',
            dataIndex: 'sex',
            // 自定义渲染
            render: (text) => {
                return text === 1 ? '男' : '女'
            }
        },
        {
            title: '出生日期',
            dataIndex: 'birth'
        },
        {
            title: '地址',
            dataIndex: 'addr'
        },
        {
            title: '操作',
            //获取当前的行的字段
            render: (rowData) => {
                return (
                    <div className="flex-box-first">
                        <Button type='default' style={{ marginRight: '5px' }} onClick={() => handleClick('edit', rowData)}>编辑</Button>
                        <Popconfirm title="你确定要删除吗?" description="此操作将永久删除该用户，是否继续？" okText="确认" cancelText="取消" onConfirm={() => handleDelete(rowData)} >
                            {/* 通过冒泡父元素触发 */}
                            <Button type='primary' danger>删除</Button>
                        </Popconfirm>

                    </div>
                )

            }
        }
    ]
    return (
        <div className="user">
            <div className="flex-box ">
                <Button type='primary' onClick={() => handleClick('add')}>+新增</Button>
                <Form
                    layout='inline'
                    onFinish={handleQuery}
                >
                    <Form.Item name="keyword">
                        <Input placeholder="请输入用户名"></Input>

                    </Form.Item>
                    <Form.Item>
                        <Button type='primary' htmlType='submit'>搜索</Button>
                    </Form.Item>

                </Form>

            </div>
            <Table rowKey={'id'} columns={columns} dataSource={tableData}></Table>

            <Modal
                open={isModalVisible}
                title={modaltype ? '编辑用户' : '新增用户'}
                onOk={handleOk}
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消"
            >
                <Form form={form}
                    labelCol={{
                        span: 6
                    }}
                    //左边标签
                    wrapperCol={{
                        span: 18
                    }}
                    //右边的内容
                    labelAlign="left"

                >
                    {

                        modaltype == 1 && <Form.Item name="id" hidden>
                            <Input ></Input>

                        </Form.Item>
                    }
                    {/* 为什么要这么写 */}


                    <Form.Item label="姓名" name="name" rules={[
                        {
                            required: true,
                            message: '请输入姓名'
                        }
                    ]}>
                        <Input placeholder="请输入姓名"></Input>
                    </Form.Item>
                    <Form.Item label="年龄" name="age" rules={[
                        {
                            type: 'number',
                            required: true,
                            message: '年龄必须是必选'

                        }
                    ]}>
                        <InputNumber placeholder="请选择" />
                    </Form.Item>
                    <Form.Item label="性别" name="sex" rules={[
                        {
                            required: true,
                            message: '请选择性别'
                        }
                    ]}>
                        <Select placeholder="请选择性别" options={[
                            {
                                label: '男',
                                value: 0
                            },
                            {
                                label: '女',
                                value: 1
                            }
                        ]}>


                        </Select>
                    </Form.Item>
                    <Form.Item label="出生日期" name="birth" rules={[
                        {
                            required: true,
                            message: '请选择出生日期'
                        }
                    ]}>
                        <DatePicker placeholder="请选择出生日期" format="YYYY/MM/DD" />
                    </Form.Item>
                    <Form.Item label="地址" name="addr" rules={[
                        {
                            required: true,
                            message: '请输入地址'
                        }
                    ]}>
                        <Input placeholder="请输入地址"></Input>
                    </Form.Item>






                </Form>
            </Modal>
        </div>
    )
}
export default User;